import axios from 'axios'
import store from '@/store'
import {
	removeItem,
} from '@/utils/storage'
import {
	Message
} from 'element-ui'
const {
	url
} = store.state
const service = axios.create({
	// baseURL: process.env.VUE_APP_BASE_API,
	baseURL: url,
	timeout: 10000
});

service.interceptors.request.use(config => {
		let token = localStorage.getItem("token");
		// let token =  sessionStorage.getItem("token");
		if (token) {
			config.headers.Authorization = JSON.parse(token).token;
			config.data.token = token;
		}
		return config
	},
	error => {
		window.console.log(error);
		return Promise.reject(error, )
	}
);

service.interceptors.response.use(
	response => {
		const res = response.data;
		if (res.code !== 1 && res.message == "请重新登录") {
			Message({
				message: res.message,
				type: 'error',
				duration: 5 * 1000
			});
			return Promise.reject(new Error(res.message || 'Error'))
		} else {
			if (res.code == 1002) {
				Message({
					message: res.msg,
					type: 'error',
					duration: 5 * 1000
				});
			} else if (res.code == 1000) {
				removeItem('token');
				removeItem('userInfo');
				// Message({
				// 	message: '请重新登录',
				// 	type: 'error',
				// 	duration: 5 * 1000
				// });
			}
			return res
		}
	},
	error => {
		let errMsg = "请求错误";
		if (error.response) {
			errMsg = error.response.data.msg || errMsg;
		}
		Message({
			message: errMsg,
			type: 'error',
			duration: 3 * 1000
		});
		// router.push('/login');
		return Promise.reject(error)
	}
);

export default service
